package one.stand.util;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author cjr
 */
public class DownLoadExcelUtil {
    public static <T> void download(HttpServletResponse response, String fileName, String sheetName, Class<T> clazz, List<T> data) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileNameEncode = URLEncoder.encode(fileName, "UTF-8") + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameEncode);
        response.setHeader("Access-Control-Expose-Headers", "x-download-file-name");
        response.setHeader("x-download-file-name", fileNameEncode);
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }
}
